package com.situ.day20.db;

import com.situ.day20.Student;
import com.situ.day20.Teacher;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Properties;

public class DBDemo {
    public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        //MySql mySql = new MySql();
        //mySql.getConnection();
        //
        //IDB db = new MySql();
        //db.getConnection();
        //db = new SqlServer();
        //db.getConnection();

        //1.通过当前的类获取类加载器
        ClassLoader classLoader = DBDemo.class.getClassLoader();
        //2.通过类加载器的方法获取输入流
        InputStream inputStream = classLoader.getResourceAsStream("db1.properties");
        Properties properties = new Properties();
        properties.load(inputStream);
        String className = properties.getProperty("className");
        //com.situ.day20.db.MySql
        Class clazz = Class.forName(className);
        Constructor constructor = clazz.getConstructor();
        IDB db = (IDB) constructor.newInstance();
        db.getConnection();

    }



    @Test
    public void test1() throws IllegalAccessException {
        Teacher teacher = new Teacher();
        System.out.println(teacher);
        changeField(teacher);
        System.out.println(teacher);

        Student student = new Student();
        student.setName("lisia");
        System.out.println(student);
        changeField(student);
        System.out.println(student);
    }

    //动态性体现在传递任意一个对象使用反射都可以完成这个功能。
    private void changeField(Object object) throws IllegalAccessException {
        //1.获得对应的Class
        Class clazz = object.getClass();
        //2.获取所有的Field[] fields
        Field[] fields = clazz.getDeclaredFields();
        //3.遍历所有的Field，如果是String类型，将包含的a改成b
        for (Field field : fields) {
            //3.1 如果是String类型才修改
            if (field.getType() == String.class) {
                //属性是私有的
                field.setAccessible(true);
                //student.getName(); 并不是调用getName，因为调用getName()要拿到对应method
                //student.name
                //3.2或者Field原来的值  "qingdao"
                String oldValue = (String) field.get(object);
                if (oldValue != null && !"".equals(oldValue)) {
                    String newValue = oldValue.replace("a", "b");
                    //3.3将修改后的值设置到Field
                    field.set(object, newValue);
                }
            }
        }
    }
}
